﻿using CleverDD.Helper;
using CleverDD.Model.Communication.PLC;
using CleverDD.Model.Param;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CleverDD.Model.Communication.SerialPort;
using System.IO.Ports;

namespace FrameWorkDemo.Communication.SerialPortFolder
{
    public partial class EditSerialPortForm : Form
    {
       

        public EditSerialPortForm()
        {
            InitializeComponent();
            InitControl();
        }




        #region 变量定义
        //避免修改参数时，直接在程序中生效，编辑类里面统一新建一个对象去修改
        private List<SerialPortInfoEntity> _serialPortInfoList = new List<SerialPortInfoEntity>();
        private int _comIndex;
        private string _currentGuid;
        #endregion

        #region 初始化
        public void InitControl()
        {
            this.MaximizeBox = false;
            this.MinimizeBox = false;

            this.StartPosition = FormStartPosition.CenterParent;

            ListView.FullRowSelect = true;
            ListView.View = View.Details;  // 设置视图为 Details 模式以显示列标题
            ListView.Dock = DockStyle.Fill;
            // 添加四列标题
            ListView.Columns.Add("ID", 0);
            ListView.Columns.Add("序号", 50);
            ListView.Columns.Add("名称", 100);
            ListView.Columns.Add("状态", 60);
            ListView.SelectedIndexChanged += new System.EventHandler(this.ListView_SelectedIndexChanged);
        }


        private void EditSerialPortForm_Load(object sender, EventArgs e)
        {
            LoadSerialPortInfoList();

            List<ParamInfo> paramList = new List<ParamInfo>
            {
                new ParamInfo("序号"),
                new ParamInfo("名称"),
            };
           

            ParamInfo param = new ParamInfo
            {
                LabelName = "串口号",
                OldValue = "",
                ParamType = ParamType.ComboBox,
                ValueList = StaticTool.GetAllPortName(),
            };
            paramList.Add(param);

            ParamInfo param2 = new ParamInfo
            {
                LabelName = "波特率",
                OldValue = "",
                ParamType = ParamType.ComboBox,
                ValueList = StaticTool.BoundList.Select(i => i.ToString()).ToList(),
            };
            paramList.Add(param2);


            ParamInfo param3 = new ParamInfo
            {
                LabelName = "校验位",
                OldValue = "",
                ParamType = ParamType.ComboBox,
                ValueList = new List<string>(Enum.GetNames(typeof(Parity))),
            };
            paramList.Add(param3);
            
            ParamInfo param4 = new ParamInfo
            {
                LabelName = "数据位",
                OldValue = "",
                ParamType = ParamType.ComboBox,
                ValueList = StaticTool.DataBitList.Select(i => i.ToString()).ToList(),
            };
            paramList.Add(param4);
            
            ParamInfo param5 = new ParamInfo
            {
                LabelName = "停止位",
                OldValue = "",
                ParamType = ParamType.ComboBox,
                ValueList = StaticTool.DataBitList.Select(i => i.ToString()).ToList(),
            };
            paramList.Add(param5);

            ParamInfo param6 = new ParamInfo
            {
                LabelName = "数据类型",
                OldValue = "",
                ParamType = ParamType.ComboBox,
                ValueList = new List<string>(Enum.GetNames(typeof(SerialPortDataType))),
            };
            paramList.Add(param6);


            ParamInfo inWaitParam = new ParamInfo
            {
                LabelName = "等待结果",
                ParamType = ParamType.YesOrNo
            };
            paramList.Add(inWaitParam);

            ParamInfo inUseParam = new ParamInfo
            {
                LabelName = "是否启用",
                ParamType = ParamType.YesOrNo
            };
            paramList.Add(inUseParam);
            BasicParamUc.InitControl(paramList);

            if (ListView.Items.Count > 0)
            {
                ListView.Items[0].Selected = true;
                ListView.EnsureVisible(0); // 确保第一行可见
                ListView.Focus();          // 设置焦点以便显示选择状态
            }
        }

        #endregion

        #region 控件方法

        private void ListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            List<string> list = new List<string>();
            if (ListView.SelectedItems.Count == 0)
            {
                _currentGuid = "";
                for (int i = 0; i < 10; i++)
                {
                    list.Add("");
                }
                BasicParamUc.InitData(list);
                return;
            }
            _comIndex = ListView.SelectedIndices[0];
            _currentGuid = this.ListView.Items[_comIndex].SubItems[0].Text.Trim();

            //根据guid找到选中的对象
            SerialPortInfoEntity selectedItem = _serialPortInfoList.FirstOrDefault(p => p.Guid == Guid.Parse(_currentGuid));
            //将选中对象的属性转成字符串的形式，传给详情界面 
            if (selectedItem != null)
            {
                list.Add(selectedItem.SortIndex + "");
                list.Add(selectedItem.Name + "");
                list.Add(selectedItem.PortName + "");
                list.Add(selectedItem.BaudRate + "");
                list.Add(selectedItem.Parity + "");
                list.Add(selectedItem.DataBits + "");
                list.Add(selectedItem.StopBits + "");
                list.Add(selectedItem.DataType + "");
                list.Add(selectedItem.IsWaitData + "");
                list.Add(selectedItem.IsInUse + "");
            }

            BasicParamUc.InitData(list);

        }


        private void NewBtn_Click(object sender, EventArgs e)
        {
            BasicParamUc.GetAllValue();
            SerialPortInfoEntity serialPortInfo = new SerialPortInfoEntity();
            serialPortInfo.Guid = Guid.NewGuid();


            int.TryParse(BasicParamUc.ParamList[0].NewValue, out int sortIndex);
            serialPortInfo.SortIndex = _serialPortInfoList.Any()
                ? Math.Max(sortIndex, _serialPortInfoList.Max(t => t.SortIndex) + 1)
                : sortIndex;

            serialPortInfo.Name = BasicParamUc.ParamList[1].NewValue;
            serialPortInfo.PortName = BasicParamUc.ParamList[2].NewValue;
            int.TryParse(BasicParamUc.ParamList[3].NewValue, out serialPortInfo.BaudRate);

            Enum.TryParse(BasicParamUc.ParamList[4].NewValue, out serialPortInfo.Parity);

            int.TryParse(BasicParamUc.ParamList[5].NewValue, out serialPortInfo.DataBits);
            Enum.TryParse(BasicParamUc.ParamList[6].NewValue, out serialPortInfo.StopBits);
            Enum.TryParse(BasicParamUc.ParamList[7].NewValue, out serialPortInfo.DataType);
            bool.TryParse(BasicParamUc.ParamList[8].NewValue, out serialPortInfo.IsWaitData);
            bool.TryParse(BasicParamUc.ParamList[9].NewValue, out serialPortInfo.IsInUse);


           


            if ("".Equals(serialPortInfo.Name))
            {
                MessageBox.Show("名称不能为空");
                return;
            }

            bool sameNameFlag = _serialPortInfoList.Any(obj => obj.Name == serialPortInfo.Name);
            bool sameNameFlag2 = _serialPortInfoList.Any(obj => obj.PortName == serialPortInfo.PortName);
            if (sameNameFlag|| sameNameFlag2)
            {
                MessageBox.Show("名称不能相同");
                return;
            }

            _serialPortInfoList.Add(serialPortInfo);
            SavaSerialPortInfoList();

        }

        private void SaveBtn_Click(object sender, EventArgs e)
        {
            if ("".Equals(_currentGuid))
            {
                MessageBox.Show("未选中数据");
                return;
            }
            BasicParamUc.GetAllValue();
            foreach (var serialPortInfo in _serialPortInfoList)
            {
                if (serialPortInfo.Guid == Guid.Parse(_currentGuid))
                {
                    int.TryParse(BasicParamUc.ParamList[0].NewValue, out serialPortInfo.SortIndex);
                    serialPortInfo.Name = BasicParamUc.ParamList[1].NewValue;
                    serialPortInfo.PortName = BasicParamUc.ParamList[2].NewValue;
                    int.TryParse(BasicParamUc.ParamList[3].NewValue, out serialPortInfo.BaudRate);
                    Enum.TryParse(BasicParamUc.ParamList[4].NewValue, out serialPortInfo.Parity);
                    int.TryParse(BasicParamUc.ParamList[5].NewValue, out serialPortInfo.DataBits);
                    Enum.TryParse(BasicParamUc.ParamList[6].NewValue, out serialPortInfo.StopBits);
                    Enum.TryParse(BasicParamUc.ParamList[7].NewValue, out serialPortInfo.DataType);
                    bool.TryParse(BasicParamUc.ParamList[8].NewValue, out serialPortInfo.IsWaitData);
                    bool.TryParse(BasicParamUc.ParamList[9].NewValue, out serialPortInfo.IsInUse);
                    break;
                }
            }
            SavaSerialPortInfoList();
        }

        private void DelBtn_Click(object sender, EventArgs e)
        {
            _serialPortInfoList.RemoveAll(p => p.Guid == Guid.Parse(_currentGuid));
            SavaSerialPortInfoList();
        }

        private void RefreshBtn_Click(object sender, EventArgs e)
        {
            LoadSerialPortInfoList();
        }

        #endregion

        #region 主要方法

        public void SavaSerialPortInfoList()
        {
            StaticTool.SavaSerialPortInfoList(_serialPortInfoList);
            LoadSerialPortInfoList();
        }


        public void LoadSerialPortInfoList()
        {
            _serialPortInfoList = StaticTool.LoadSerialPortInfoList();
            this.ListView.Items.Clear();
            foreach (var item in _serialPortInfoList)
            {
                ListViewItem lvi = new ListViewItem
                {
                    Text = item.Guid + ""
                };
                lvi.SubItems.Add(item.SortIndex + "");
                lvi.SubItems.Add(item.Name);
                lvi.SubItems.Add(item.IsInUse ? "启用" : "停用");
                this.ListView.Items.Add(lvi);
            }
        }

        #endregion

       
    }
}
